package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.CustomerDao;
import com.atguigu.jxc.entity.Customer;
import com.atguigu.jxc.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDao customerDao;

    @Override
    public void save(Customer customer) {
        Integer customerId = customer.getCustomerId();
        if (customerId != null){
            customerDao.update(customer);
        }else {
            customerDao.insert(customer);
        }
    }

    @Override
    public void delete(String ids) {
        List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        customerDao.delete(list);
    }

    @Override
    public Map<String, Object> getCustomerList(Integer page, Integer rows, String customerName) {
        Map<String, Object> map = new HashMap<>();
        List<Customer> customerList = customerDao.selectCustomList(customerName);
        Integer total = customerDao.selectTotal(customerName);
        int firstIndex = (page - 1) * rows;
        int lastIndex = page * rows;
        if (total < lastIndex){
            lastIndex = total;
        }
        List<Customer> customerListPage = customerList.subList(firstIndex, lastIndex);
        map.put("rows",customerListPage);
        map.put("total",total);
        return map;
    }
}
